const { Service } = require("uni-cloud-router");
const uniID = require('uni-id');
const response=require("../utils/response.js");
const db = uniCloud.database({
	spaceId: 'b33db069-91a2-42ff-a831-31fbd5a04b97'
});
const dbCmd = db.command;
const collection=db.collection("goods_cart");
module.exports = class CartService extends Service {
  async add(){
		const { ctx, service } = this;
		const res=await collection.where({
			sku_id:ctx.data.sku_id,
			user_id:ctx.uid
		}).limit(1).get()
		if(res.affectedDocs>0){
			ctx.data.count+=res.data[0].count
			const res1=await collection.doc(res.data[0]._id).update(ctx.data);
			if(res1.affectedDocs>0){
				return response.success(res.data[0]._id);
			}else{
				return response.fail('修改失败');
			}
		}else{
			const res1=await collection.add(Object.assign({
				user_id:ctx.uid
			},ctx.data));
			if(res1.id){
				return response.success(res1);
			}else{
				return response.fail('添加失败');
			}
		}
  	
  }
  async list(){
		const { ctx, service } = this;
  	const res=await collection.where({
			user_id:ctx.uid
		}).get();
		if(res.affectedDocs>=0){
			return response.success(res.data);
		}else{
			return response.fail('查询失败');
		}
  }
	async getByIDs(){
		const { ctx, service } = this;
		const res=await collection.where({
			user_id:ctx.uid,
			_id:dbCmd.in(ctx.data)
		}).get();
		if(res.affectedDocs>=0){
			return response.success(res.data);
		}else{
			return response.fail('查询失败');
		}
	}
	async edit(){
		const { ctx, service } = this;
		const id=ctx.data._id
		delete ctx.data._id
		delete ctx.data.user_id
		const res=await collection.where({
			user_id:ctx.uid,
			_id:id
		}).update(ctx.data)
		if(res.affectedDocs>=0){
			return response.success(res.data);
		}else{
			return response.fail('查询失败');
		}
	}
  async delete(){
		const { ctx, service } = this;
  	const res=await collection.where({
			_id: dbCmd.in(ctx.data.ids)
		}).remove();
		if(res.affectedDocs>=0){
			return response.success(res.data);
		}else{
			return response.fail('删除失败');
		}
  }
};